package com.lyj.linearalgebra.admin.service;

import java.util.List;
import java.util.Map;

import com.lyj.linearalgebra.admin.dao.AdminDao;
import com.lyj.linearalgebra.admin.domain.Admin;
import com.lyj.linearalgebra.post.domain.Posts;
import com.lyj.linearalgebra.user.domain.User;


public class AdminService {
	
	private AdminDao adminDao = new AdminDao();

	public Admin login(Admin form) throws AdminException {
		Admin admin = adminDao.findByUsername(form.getUsername());
		if(admin == null) {
			throw new AdminException("用户名不存在!");
		}else if(!admin.getPassword().equals(form.getPassword())) {
			throw new AdminException("密码错误!");
		}
		return admin;
	}

	public void reset(String aid,String password) {
		adminDao.reset(aid,password);
		
	}

	public void resetInfo(Admin admin, Map<String, String> form) throws AdminException {
		
		if(admin.getUsername().equals(form.get("username")) && (form.get("email") == null || form.get("email").trim().isEmpty())) {
			throw new AdminException("信息与原信息一致!");
		}
		
		if(admin.getEmail().equals(form.get("email")) && (form.get("username") == null || form.get("username").trim().isEmpty())) {
			throw new AdminException("信息与原信息一致!");
		}
		
		if(admin.getUsername().equals(form.get("username")) && admin.getEmail().equals(form.get("email"))) {
			throw new AdminException("信息与原信息一致!");
		}
		
		if(!admin.getUsername().equals(form.get("username"))) {
			Admin temp = adminDao.findByUsername(form.get("username"));
			if(temp != null) {
				throw new AdminException("用户名已被注册!");
			}
		}
		if(!admin.getEmail().equals(form.get("email"))) {
			Admin temp = adminDao.findByEmail(form.get("email"));
			if(temp != null) {
				throw new AdminException("邮箱已被注册!");			
			}
		}
		adminDao.resetInfo(admin,form.get("username"),form.get("emai"));
		
	}

	public List<User> findAllUsers() {
		return adminDao.findAllUsers();
	}

	public void deleteUser(String uid) {
		adminDao.deleteUser(uid);
	}

	public List<Posts> getAllPosts() {
		return adminDao.getAllPosts();
	}

	public void deletePost(String pid) {
        adminDao.deletePost(pid);
		
	}

	public void addManager(Admin form) throws AdminException {
		Admin admin = adminDao.findByUsername(form.getUsername());
		if(admin != null) {
			throw new AdminException("用户名已存在!");
		}
		admin = adminDao.findByEmail(form.getEmail());
		if(admin != null) {
			throw new AdminException("邮箱已存在!");
		}
		adminDao.addManager(form);
		
	}

}
